<script setup lang="ts">
import { ContentWrap } from '@/components/ContentWrap'
import { Search } from '@/components/Search'
import { ElButton, ElLoading } from 'element-plus'
import { Table } from '@/components/Table'
// import { adminCsOrderListApi } from '@/api/cs/order'
// import { ucOrgListApi } from '@/api/uc/org'
// import { ucUserListAdminApi } from '@/api/uc/user'
import { adminCsClassListApi } from '@/api/cs/class'
import { useTable } from '@/hooks/web/useTableTest'
import { TableData } from '@/api/cs/order/types'
import { ref, reactive } from 'vue'
import { CrudSchema, useCrudSchemas } from '@/hooks/web/useCrudSchemas'

// 获取字典
import { useCache } from '@/hooks/web/useCache'
import { dbCsOrderListApi, dbCsOrderexportApi } from '@/api/forms'
import { ucOrgListApi } from '@/api/uc/org'
const { wsCache } = useCache()
const dict: any = wsCache.get('dict')
// 字典通过value获取label
const getDictLabel = (type, value) => {
  let data = dict[type].find((item) => {
    return item.value == value
  })
  return data ? data.label : ''
}

const { register, tableObject, methods } = useTable<
  {
    total: number
    list: TableData[]
  },
  any
>({
  getListApi: dbCsOrderListApi,
  response: {
    data: 'data',
    count: 'count'
  }
})

const { setSearchParams } = methods

// 所属分类
const newClassData = ref<any[]>([])
const getClassList = async () => {
  const loadingMain = ElLoading.service({
    lock: true,
    text: 'Loading',
    background: 'rgba(0, 0, 0, 0.7)'
  })
  const res = await adminCsClassListApi({})
    .catch(() => {})
    .finally(() => {
      setTimeout(() => {
        loadingMain.close()
      }, 500)
    })
  if (res) {
    newClassData.value = [{ class_id: '0', class_name: ' ' }, ...res.data]
  }
}
getClassList()

const crudSchemas = reactive<CrudSchema[]>([
  {
    field: 'index',
    label: '序号',
    fixed: 'left',
    type: 'index',
    width: 60,
    table: {
      show: true
    },
    form: {
      show: false
    },
    detail: {
      show: false
    }
  },
  {
    field: 'buy_org_id',
    label: '买方组织',
    search: {
      component: 'DialogRefer',
      componentProps: {
        getListApi: ucOrgListApi,
        response: {
          count: 'count',
          data: 'data'
        },
        title: '选择组织（双击选择）',
        nameField: 'buy_org_name',
        relNameField: 'org_name',
        valueField: 'buy_org_id',
        relValueField: 'org_id',
        crudSchemas: [
          {
            field: 'org_name',
            label: '组织名称',
            fixed: 'left',
            search: {
              show: true
            }
          }
        ]
      },
      show: true
    },
    form: {
      component: 'DialogRefer',
      componentProps: {
        getListApi: ucOrgListApi,
        response: {
          count: 'count',
          data: 'data'
        },
        title: '选择组织（双击选择）',
        nameField: 'buy_org_name',
        relNameField: 'org_name',
        valueField: 'buy_org_id',
        relValueField: 'org_id',
        crudSchemas: [
          {
            field: 'org_name',
            label: '组织名称',
            fixed: 'left',
            search: {
              show: true
            }
          }
        ]
      },
      show: true
    },
    table: {
      show: false
    },
    detail: {
      show: false
    }
  },
  {
    field: 'buy_org_name',
    label: '卖方组织',
    width: 150,
    form: {
      show: true
    }
  },
  {
    field: 'sell_org_name',
    label: '卖方组织',
    width: 150,
    form: {
      show: true
    }
  },
  {
    field: 'sell_org_id',
    label: '卖方组织',
    search: {
      component: 'DialogRefer',
      componentProps: {
        getListApi: ucOrgListApi,
        response: {
          count: 'count',
          data: 'data'
        },
        title: '选择组织（双击选择）',
        nameField: 'sell_org_name',
        relNameField: 'org_name',
        valueField: 'sell_org_id',
        relValueField: 'org_id',
        crudSchemas: [
          {
            field: 'org_name',
            label: '组织名称',
            fixed: 'left',
            search: {
              show: true
            }
          }
        ]
      },
      show: true
    },
    form: {
      component: 'DialogRefer',
      componentProps: {
        getListApi: ucOrgListApi,
        response: {
          count: 'count',
          data: 'data'
        },
        title: '选择组织（双击选择）',
        nameField: 'sell_org_name',
        relNameField: 'org_name',
        valueField: 'sell_org_id',
        relValueField: 'org_id',
        crudSchemas: [
          {
            field: 'org_name',
            label: '组织名称',
            fixed: 'left',
            search: {
              show: true
            }
          }
        ]
      },
      show: true
    },
    table: {
      show: false
    },
    detail: {
      show: false
    }
  },
  {
    field: 'sell_org_name',
    label: '卖方组织',
    width: 150,
    form: {
      show: false
    }
  },
  {
    field: 'order_group_sn',
    label: '订单组编号',
    width: 180,
    form: {
      show: true
    }
  },
  {
    field: 'order_sn',
    label: '订单编号',
    width: 180,
    search: {
      show: true
    }
  },
  {
    field: 'payable_price',
    label: '应付金额',
    width: 100,
    form: {
      show: false
    }
  },

  {
    field: 'paid_price',
    label: '实付金额',
    width: 100,
    form: {
      show: false
    }
  },
  {
    field: 'order_status',
    label: '订单状态',
    width: 100,
    formatter: (_: Recordable, __: TableColumn, cellValue: number | string) => {
      return cellValue != '0' ? getDictLabel('cs_order_status', cellValue) : ' '
    },
    form: {
      component: 'Select',
      componentProps: {
        options: dict.cs_order_status
      }
    },
    search: {
      component: 'Select',
      componentProps: {
        options: dict.cs_order_status
      },
      show: true
    }
  },
  {
    field: 'shipping_status',
    label: '发货状态',
    width: 100,
    formatter: (_: Recordable, __: TableColumn, cellValue: number | string) => {
      return cellValue != '0' ? getDictLabel('cs_shipping_status', cellValue) : ' '
    },
    form: {
      component: 'Select',
      componentProps: {
        options: dict.cs_shipping_status
      }
    },
    search: {
      component: 'Select',
      componentProps: {
        options: dict.cs_shipping_status
      },
      show: true
    }
  },
  {
    field: 'pay_status',
    label: '支付状态',
    width: 100,
    formatter: (_: Recordable, __: TableColumn, cellValue: number | string) => {
      return cellValue != '0' ? getDictLabel('cs_pay_status', cellValue) : ' '
    },
    form: {
      component: 'Select',
      componentProps: {
        options: dict.cs_pay_status
      }
    },
    search: {
      component: 'Select',
      componentProps: {
        options: dict.cs_pay_status
      },
      show: true
    }
  },
  {
    field: 'buy_user_name',
    label: '创建人',
    form: {
      show: false
    },
    search: {
      show: true
    }
  },
  {
    field: 'create_time',
    label: '创建时间',
    width: 170,
    form: {
      show: true,
      component: 'DatePicker',
      componentProps: {
        disabled: true,
        type: 'datetime',
        valueFormat: 'YYYY-MM-DD HH:mm:ss'
      }
    },
    search: {
      show: true,
      component: 'DatePicker',
      componentProps: {
        'is-range': true,
        'unlink-panels': true,
        rangeSeparator: 'To',
        type: 'daterange',
        valueFormat: 'YYYY-MM-DD HH:mm:ss'
      }
    }
  }
])

const { allSchemas } = useCrudSchemas(crudSchemas)

const exportClick = async () => {
  dialogTableVisible.value = true
  let aaa: any = tableObject.paramsObj.params
  console.log(aaa)

  let res: any = await dbCsOrderListApi({
    // pasture_org_id: aaa.pasture_org_id,
    ...tableObject.paramsObj.params
  })
    .catch(() => {})
    .finally(() => {})
  if (res) {
    FormsNumber.value = Math.ceil(res.count / 10000)
  }
}

const FormsNumber = ref(0)
const dialogTableVisible = ref(false)

const Export = async (index) => {
  // let aaa: any = tableObject.paramsObj.params
  let { data }: any = await dbCsOrderexportApi({
    request: {
      // buy_org_id: aaa.buy_org_id,
      // order_sn: aaa.order_sn,
      // order_status: aaa.order_status,
      // pay_status: aaa.pay_status,
      // shipping_status: aaa.shipping_status,
      ...tableObject.paramsObj.params,
      pageNo: index,
      pageSize: '10000'
    },
    layout_data: {
      file_name: '订单列表',
      column_cell_start: 'A2',
      column_data: [
        {
          title: '序号',
          width: 5,
          cell_type: 'key'
        },
        {
          title: '买方组织',
          width: 20,
          cell_type: 'string',
          give_type: 'variable',
          give_value: 'buy_org_name'
        },
        {
          title: '买房用户',
          width: 20,
          cell_type: 'string',
          give_type: 'variable',
          give_value: 'buy_user_name'
        },
        {
          title: '卖方组织',
          width: 20,
          cell_type: 'string',
          give_type: 'variable',
          give_value: 'sell_org_name'
        },
        {
          title: '订单组编号',
          width: 20,
          cell_type: 'string',
          give_type: 'variable',
          give_value: 'order_group_sn'
        },
        {
          title: '订单编号',
          width: 20,
          cell_type: 'string',
          give_type: 'variable',
          give_value: 'order_sn'
        },
        {
          title: '应付金额',
          width: 15,
          cell_type: 'number',
          decimal: 2,
          give_type: 'variable',
          give_value: 'payable_price',
          sum: true
        },
        {
          title: '实付金额',
          width: 15,
          cell_type: 'number',
          decimal: 2,
          give_type: 'variable',
          give_value: 'paid_price',
          sum: true
        },
        {
          title: '订单状态',
          width: 10,
          cell_type: 'dict',
          dict_type: 'cs_order_status',
          give_type: 'variable',
          give_value: 'order_status'
        },
        {
          title: '发货状态',
          width: 10,
          cell_type: 'dict',
          dict_type: 'cs_shipping_status',
          give_type: 'variable',
          give_value: 'shipping_status'
        },
        {
          title: '支付状态',
          width: 10,
          cell_type: 'dict',
          dict_type: 'cs_pay_status',
          give_type: 'variable',
          give_value: 'pay_status'
        },
        {
          title: '创建时间',
          width: 20,
          cell_type: 'string',
          give_type: 'variable',
          give_value: 'create_time'
        }
      ],
      custom: [
        {
          cell_type: 'string',
          cell: 'A1:L1',
          give_type: 'format',
          give_value: '订单列表',
          horizontal: 'center',
          border: true,
          size: '16'
        }
      ]
    }
  })
    .catch(() => {})
    .finally(() => {
      // saveLoading.value = false
    })
  if (data) {
    window.open(data.url)

    console.log(data, Math.ceil(data.count / 10000))
    // FormsNumber.value = Math.ceil(data.count / 10000)
  }
}
</script>

<template>
  <ContentWrap>
    <Search :schema="allSchemas.searchSchema" @search="setSearchParams" @reset="setSearchParams" />
    <div class="mb-10px w-[100%] flex justify-end" v-show="tableObject.paramsObj.params">
      <ElButton type="primary" @click="exportClick()"> 导出EXCEL </ElButton>
    </div>
    <Table
      v-show="tableObject.paramsObj.params"
      v-model:pageSize="tableObject.pageSize"
      v-model:currentPage="tableObject.currentPage"
      :columns="allSchemas.tableColumns"
      :data="tableObject.tableList"
      :loading="tableObject.loading"
      :border="true"
      :pagination="{
        total: tableObject.count
      }"
      @register="register"
      :selection="false"
    />
  </ContentWrap>

  <el-dialog v-model="dialogTableVisible" title="订单主档导出详情">
    <div style="margin: 20px" v-for="(item, index) in FormsNumber" :key="index">
      <span style="margin: 20px">订单主档 - {{ item }}</span>
      <ElButton type="primary" @click="Export(item)">导出</ElButton>
    </div>
  </el-dialog>
</template>
